package com.moqianfan.mcuassistant.activity;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.moqianfan.mcuassistant.R;
import com.moqianfan.mcuassistant.bean.Collec;
import com.moqianfan.mcuassistant.database.CollecDao;
import com.moqianfan.mcuassistant.utils.LogUtil;
import com.moqianfan.mcuassistant.view.MessageDialog;

import net.youmi.android.os.PointsManager;

import org.greenrobot.greendao.query.QueryBuilder;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/6/15.
 * web加载
 */

public class WebInfoActivity extends BaseActivity {
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.web_info)
    WebView webInfo;
    @BindView(R.id.image_coll)
    ImageView imageColl;

    private Document doc;
    private ProgressDialog dialog;
    private String url;
    private String html;
    private String picUrl;
    private String title;
    private String desc;
    private CollecDao collecDao;
    private Collec collec;
    private boolean isCollec = false;
    private MessageDialog msgDialog;
    private final static Calendar calendar = Calendar.getInstance();
    private String day;

    private String TAG = "WebInfoActivity";

    @Override
    public void findViews() {
        setContentView(R.layout.activity_web_info);
        dialog = new ProgressDialog(this);
        dialog.setMessage("正在加载,请稍后...");
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        day = "" + calendar.get(Calendar.DATE);
        LogUtil.d(TAG, "day=" + day);
    }

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    public void initViews() {
        title = getIntent().getStringExtra("title");
        html = getIntent().getStringExtra("html");
        url = getIntent().getStringExtra("url");
        picUrl = getIntent().getStringExtra("picUrl");
        desc = getIntent().getStringExtra("desc");
        String head = getIntent().getStringExtra("head");
        txtTitle.setText(TextUtils.isEmpty(head) ? title : head);
        LogUtil.w(TAG, "url=" + url);
        if (getIntent().getIntExtra("flag", -1) == 0) {
            webInfo.loadUrl(url);
        } else {
            //扣除一点积分
            userPreference.edit().putInt(day, userPreference.getInt(day, -100) - 1).apply();
            LogUtil.d(TAG, "剩余可读次数：" + userPreference.getInt(day, -100));
            if (userPreference.getInt(day, -100) <= 0)
                if (PointsManager.getInstance(this).spendPoints(1)) {
                    LogUtil.d(TAG, "扣除成功：" + PointsManager.getInstance(this).queryPoints());
                } else {
                    LogUtil.d(TAG, "扣除失败：" + PointsManager.getInstance(this).queryPoints());
                    showDialog();
                }

            if (!TextUtils.isEmpty(html)) {
                LogUtil.w(TAG, "html=" + html);
                if (html.contains("下一课")) {
                    LogUtil.w(TAG, "包含下一课标签");
                    html = html.substring(0, html.lastIndexOf("<p>")) + "</div>";
                }
                webInfo.loadDataWithBaseURL(null, handleHtml(html), "text/html", "utf-8", null);
            } else {
                getJsoupUrl();
            }
        }

        webInfo.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webInfo.getSettings().setLoadWithOverviewMode(true);
        webInfo.getSettings().setJavaScriptEnabled(true);
        webInfo.getSettings().setDefaultTextEncodingName("UTF-8");
        webInfo.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String newUrl) {
                if (newUrl.startsWith("http://") || newUrl.startsWith("https://")) {
                    if (newUrl.contains("www.85nian.net")) {
                        view.stopLoading();
                        url = newUrl;
                        getJsoupUrl();
                    } else {
                        view.loadUrl(newUrl);
                    }
                    return true;
                } else {
                    view.loadDataWithBaseURL(url, null, "text/html", "utf-8", null);
                    return false;
                }
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                LogUtil.e(TAG, "开始加载");
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                LogUtil.e(TAG, "加载完成");
                if (null != dialog && dialog.isShowing())
                    dialog.dismiss();
            }
        });
    }

    @Override
    public void initDatas() {
        collecDao = appConfig.getDaoSession().getCollecDao();
        QueryBuilder qb = collecDao.queryBuilder();
        qb.where(CollecDao.Properties.Title.eq(title));
        List list = qb.list();
        if (list.size() > 0) {
            collec = (Collec) list.get(0);
            imageColl.setImageResource(R.drawable.ic_coll_yes);
            isCollec = true;
        } else {
            imageColl.setImageResource(R.drawable.ic_coll);
            isCollec = false;
        }
    }

    @OnClick({R.id.image_close, R.id.image_coll})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.image_close:
                finish();
                break;
            case R.id.image_coll:
                if (isCollec) {
                    collecDao.delete(collec);
                    isCollec = false;
                    imageColl.setImageResource(R.drawable.ic_coll);
                } else {
                    isCollec = true;
                    imageColl.setImageResource(R.drawable.ic_coll_yes);
                    collec = new Collec();
                    collec.setDesc(desc);
                    if (!TextUtils.isEmpty(url))
                        collec.setUrl(url);
                    else
                        collec.setHtml(html);
                    collec.setTitle(title);
                    collec.setPicUrl(picUrl);
                    collecDao.insert(collec);
                    LogUtil.e(TAG, "" + collec.toString());
                }
                break;
        }
    }

    /**
     * 自适应图片
     *
     * @param html html
     * @return 设置好图片的html
     */
    private String handleHtml(String html) {
        Document doc_Dis = Jsoup.parse(html);
        Elements ele_Img = doc_Dis.getElementsByTag("img");
        if (ele_Img.size() != 0) {
            for (Element e_Img : ele_Img) {
                e_Img.attr("style", "width:100%");
                e_Img.attr("abs:href");
            }
        }
        return doc_Dis.toString();
    }

    private void getJsoupUrl() {
        LogUtil.w(TAG, "加载url链接");
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    doc = Jsoup.connect(url).get();
                    if (url.contains("51hei"))
                        handler.sendEmptyMessage(0xAAA);
                    else if (url.contains("biancheng"))
                        handler.sendEmptyMessage(0xDDD);
                    else if (url.contains("www.85nian.net"))
                        handler.sendEmptyMessage(0xEEE);
                    else
                        handler.sendEmptyMessage(0xBBB);
                } catch (IOException e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(0xCCC);
                }
            }
        }).start();
    }

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 0xAAA:
                    html = handleHtml(doc.getElementById("article-content").html());
                    if (!TextUtils.isEmpty(html))
                        webInfo.loadDataWithBaseURL(null, handleHtml(html), "text/html; charset=UTF-8", null, null);
                    break;
                case 0xBBB:
                    html = doc.getElementsByClass("article-body").html();
                    if (!TextUtils.isEmpty(html))
                        webInfo.loadDataWithBaseURL(null, handleHtml(html), "text/html; charset=UTF-8", null, null);
                    break;
                case 0xDDD:
                    html = doc.getElementById("art-body").html();
                    if (!TextUtils.isEmpty(html))
                        webInfo.loadDataWithBaseURL(null, handleHtml(html), "text/html; charset=UTF-8", null, null);
                    break;
                case 0xEEE:
                    webInfo.getSettings().setJavaScriptEnabled(false);
                    html = doc.getElementById("zoom").html();
                    LogUtil.e(TAG, "去广告前：" + html);
                    html = html.replaceAll("<ins[A-Za-z0-9_\n\r]*</ins>", "");
                    html = html.replaceAll("<footer class[A-Za-z0-9_\n\r]*</footer>", "");
                    LogUtil.e(TAG, "去广告后：" + html);
                    if (!TextUtils.isEmpty(html))
                        webInfo.loadDataWithBaseURL(null, handleHtml(html), "text/html; charset=UTF-8", null, null);
                    break;
                case 0xCCC:
                    showToastShort("网络不好~");
                    break;
            }
            if (null != dialog && dialog.isShowing())
                dialog.dismiss();
            return true;
        }
    });

    private void showDialog() {
        if (null == msgDialog) {
            msgDialog = new MessageDialog(this);
            msgDialog.setCanceledOnTouchOutside(false);
            msgDialog.setCustomDialog("您的U币余额不足，请去：我的->我的积分里做任务赚取", "", "知道了");
        }
        msgDialog.setOnPositiveListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (msgDialog.isShowing())
                    msgDialog.dismiss();
                finish();
            }
        });
        if (null != msgDialog && !msgDialog.isShowing())
            msgDialog.show();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != dialog) {
            dialog.cancel();
            dialog = null;
        }
    }
}
